import express from 'express';
import { HotelService } from '../../service';
import type { HotelData } from '../../types/DataTypes';

const router = express.Router();

// 获取所有酒店
router.get('/', async (req, res) => {
    try {
        const hotels = await HotelService.getAllHotels();
        res.json({
            success: true,
            data: hotels,
            count: hotels.length
        });
    } catch (error) {
        console.error('获取酒店列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取酒店列表失败'
        });
    }
});

// 高级搜索酒店（支持位置、价格范围）
router.get('/search/advanced', async (req, res) => {
    try {
        const {
            location,
            minPrice,
            maxPrice,
        } = req.query;

        // 至少需要一个搜索条件
        if (!location && minPrice === undefined && maxPrice === undefined) {
            return res.status(400).json({
                success: false,
                message: '请至少提供一个搜索条件（位置或价格范围）'
            });
        }

        const hotels = await HotelService.advancedSearch({
            location: location as string,
            minPrice: minPrice !== undefined ? Number(minPrice) : undefined,
            maxPrice: maxPrice !== undefined ? Number(maxPrice) : undefined
        });

        res.json({
            success: true,
            data: hotels,
            count: hotels.length
        });
    } catch (error) {
        console.error('高级搜索酒店失败:', error);
        res.status(500).json({
            success: false,
            message: '高级搜索酒店失败'
        });
    }
});

// 添加新酒店
router.post('/', async (req, res) => {
    try {
        const { location, price, totalRoom, availRoom }: HotelData = req.body;

        // 验证必填字段
        if (!location || price < 0 || totalRoom <= 0) {
            return res.status(400).json({
                success: false,
                message: '输入参数错误'
            });
        }

        const hotelData: HotelData = {
            location,
            price: Number(price),
            totalRoom: Number(totalRoom),
            availRoom: availRoom !== undefined ? Number(availRoom) : Number(totalRoom)
        };

        const success = await HotelService.addHotel(hotelData);

        if (success) {
            res.status(201).json({
                success: true,
                message: '酒店添加成功',
                data: hotelData
            });
        } else {
            res.status(500).json({
                success: false,
                message: '酒店添加失败'
            });
        }
    } catch (error: any) {
        console.error('添加酒店失败:', error);

        if (error.message.includes('已存在')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        } else {
            res.status(500).json({
                success: false,
                message: '添加酒店失败'
            });
        }
    }
});

// 更新酒店信息
router.put('/update', async (req, res) => {
    try {
        const hotelData: HotelData = req.body;

        // 验证必填字段
        if (!hotelData.location) {
            return res.status(400).json({
                success: false,
                message: '酒店位置不能为空'
            });
        }

        const success = await HotelService.updateHotel(hotelData);

        if (success) {
            res.json({
                success: true,
                message: '酒店信息更新成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '酒店不存在或更新失败'
            });
        }
    } catch (error) {
        console.error('更新酒店信息失败:', error);
        res.status(500).json({
            success: false,
            message: '更新酒店信息失败'
        });
    }
});

// 酒店可用房间数量+1
router.patch('/:location/increment', async (req, res) => {
    try {
        const { location } = req.params;

        const success = await HotelService.incrementHotelAvailability(location);

        if (success) {
            res.json({
                success: true,
                message: '酒店可用房间+1成功'
            });
        } else {
            res.status(400).json({
                success: false,
                message: '酒店不存在或可用房间已达上限'
            });
        }
    } catch (error) {
        console.error('增加酒店可用房间失败:', error);
        res.status(500).json({
            success: false,
            message: '增加酒店可用房间失败'
        });
    }
});

// 酒店可用房间数量-1
router.patch('/:location/decrement', async (req, res) => {
    try {
        const { location } = req.params;

        const success = await HotelService.decrementHotelAvailability(location);

        if (success) {
            res.json({
                success: true,
                message: '酒店可用房间-1成功'
            });
        } else {
            res.status(400).json({
                success: false,
                message: '酒店不存在或可用房间已为0'
            });
        }
    } catch (error) {
        console.error('减少酒店可用房间失败:', error);
        res.status(500).json({
            success: false,
            message: '减少酒店可用房间失败'
        });
    }
});

// 删除酒店
router.delete('/:location', async (req, res) => {
    try {
        const { location } = req.params;

        const success = await HotelService.deleteHotel(location);

        if (success) {
            res.json({
                success: true,
                message: '酒店删除成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '酒店不存在或删除失败'
            });
        }
    } catch (error) {
        console.error('删除酒店失败:', error);
        res.status(500).json({
            success: false,
            message: '删除酒店失败'
        });
    }
});

export default router;